<?php

namespace app\admin\tool;


/**
 * $data 的数据结构必须包含 key pKey 并且$data 以key 为键
 * Class Tree
 * @package app\admin\tool
 */
class Tree{

    private $data;
    private $key;
    private $pKey;
    private $sub;

    public function __construct($data,$key,$pKey,$sub='sub')
    {
        $this->data = $data;
        $this->key = $key;
        $this->pKey= $pKey;
        $this->sub = $sub;
    }

    /**
     * 每一个getTree 都返回下级树
     * 适合 在数据量少的时候 或者层级少的时候
     * @param int $pKeyValue
     * @return array
     */
    private function getSub($pKeyValue=0){
        $tmp = [];
        foreach($this->data as $key => $val ){
            if($val[$this->pKey] == $pKeyValue){
                $tmp[] = $val;
                unset($this->data[$key]);
            }
        }
        foreach($tmp as $key => &$val ){
            $val[$this->sub] = $this->getSub($val[$this->key]);
        }
        unset($val);

        return $tmp;
    }

    public function getTree(){
        return  $this->getSub();
    }
}